package sg.edu.nus.iss.billing.dao.bill;

import java.util.ArrayList;
import java.util.Date;

import sg.edu.nus.iss.billing.common.DbUtil;
import sg.edu.nus.iss.billing.common.exception.BadDbCallException;
import sg.edu.nus.iss.billing.vo.bill.BillDetailVO;

/**
 * @author Chee Ann
 *
 */
public class BillDAO implements IBillDAO {
	private ArrayList<String> data = null;
	private final static String FILE_PATH = "data//bill.txt";
	
	public BillDAO(){
		try {
			data = (ArrayList<String>) DbUtil.loadDb(FILE_PATH);
		} catch (BadDbCallException e) {
			data = new ArrayList<String>();
			System.out.println(e.getMessage());
		}
	}
	
	public void printDb(){
		for (int i=0;i<data.size();i++ ){
			System.out.println(data.get(i));
		}
	}

	@Override
	public void createBill(BillDetailVO bill) throws BadDbCallException {
		data.add(bill.serialised());
		DbUtil.saveDb(FILE_PATH, data);
	}
	
	@Override
	public void updateBill(BillDetailVO bill) throws BadDbCallException {
		for (int i=0; i<data.size(); i++) {
			String[] tokens =  (data.get(i)).split(java.util.regex.Pattern.quote("^"));
			BillDetailVO thisBill = new BillDetailVO(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]);
			if (thisBill.getAccountNo().equals(bill.getAccountNo())) {
				if (thisBill.getBillDate().equals(thisBill.getBillDate())) {
					data.set(i, bill.serialised());
					DbUtil.saveDb(FILE_PATH, data);
					break;
				}
			}
		}
	}

	@Override
	public void removeBill(String accountNo, Date billDate) throws BadDbCallException {
		for (int i=0; i<data.size(); i++) {
			String[] tokens =  (data.get(i)).split(java.util.regex.Pattern.quote("^"));
			BillDetailVO thisBill = new BillDetailVO(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]);
			if (thisBill.getAccountNo().equals(accountNo)) {
				if (thisBill.getBillDate().toString().equals(billDate.toString())) {
					data.remove(i);
					DbUtil.saveDb(FILE_PATH, data);
					break;
				}
			}
		}
	}

	@Override
	public BillDetailVO getBill(String accountNo, Date billDate) {
		for (int i=0; i<data.size(); i++) {
			String[] tokens =  (data.get(i)).split(java.util.regex.Pattern.quote("^"));
			BillDetailVO thisBill = new BillDetailVO(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]);
			if (thisBill.getAccountNo().equals(accountNo)) {
				if(billDate.toString().equals(thisBill.getBillDate().toString())){
					return thisBill;
				}
			}
		}
		return null;
	}
}
